<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import questionModel from './_components/question-model.vue';
import TradeList from './_components/trade-list.vue';

const { t } = useI18n()
definePageMeta({
  layout: 'header-back',
  title: '交易记录'
});

const showQuestionModal = ref(false)
// const tabList = [
//   { label: t('tab_all') },
//   { label: t('tab_manual_deposit') },
//   { label: t('tab_fiat_in') },
//   { label: t('tab_fiat_out') },
// ]
const tabList = computed(() => {
  if (selectedAct.value !== '2') return []
  
  const types = new Set(financeRecordOther.data.value?.d?.map(item => item.cash_type_name) || [])
  return [
    { label: t('all') },
    ...Array.from(types).map(type => ({ label: type }))
  ]
})

const activeTab = ref(0)
const setTab = (idx: number) => {
  activeTab.value = idx
}

const otherOptions = [
  { label: t('deposit'), value: '0' },
  { label: t('withdraw'), value: '1' },
  { label: t('other'), value: '2' }
]
const timeOptions = [
  { label: t('last_60_days'), value: '0' },
  { label: t('last_30_days'), value: '1' },
  { label: t('last_7_days'), value: '2' },
  { label: t('last_24_hours'), value: '3' },
  { label: '2024/12/18 - 2024/12/25', icon: '', value: 'trade-date' },
  // ... 其他选项
]
const assetOptions = [
  { label: t('fiat'), value: '0' },
  { label: t('crypto'), value: 'crypto' },
  // ... 其他选项
]
const typeOptions = [
  { label: t('all_types'), value: '0' },
  { label: t('success'), value: '1' },
  { label: t('failed'), value: '2' },
  { label: t('processing'), value: '3' },
  // ... 其他选项
]

const dynamicAssetOptions = computed(() => {
  // if (selectedAct.value === '2') {
  //   return [
  //     { label: t('all'), value: '0' },
  //     { label: t('deposit_bonus'), value: '1' },
  //     { label: t('red_packet'), value: '2' }
  //   ]
  // }
  return assetOptions
})

const selectedAct = ref('0')
const selectedTime = ref('trade-date')
const selectedAsset = ref('0')
const selectedType = ref('0')
const dateRange = ref('')


// 加密货币存款
const recordDepositCoin = useList(ApiFinanceRecordDepositCoin,
  { manual: true }, { page_size: 10 })
// 法定货币存款
const recordDepositBank = useList(ApiFinancRecordDepositBank,
  { manual: true }, { page_size: 10 })
// 加密货币取款
const recordWithdrawCoin = useList(ApiFinanceRecordWithdrawCoin,
  { manual: true }, { page_size: 10 })
// 法定货币取款
const recordWithdrawBank = useList(ApiFinanceRecordWithdrawBank,
  { manual: true }, { page_size: 10 })
// 其他
const financeRecordOther = useList(ApiFinanceRecordOther,
  { manual: true }, { page_size: 10 })

function formatTimestamp(ts: number | string | undefined): string {
  if (!ts) return ''
  const date = new Date(Number(ts) * 1000)
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const min = String(date.getMinutes()).padStart(2, '0')
  return `${y}/${m}/${d} ${h}:${min}`
}

function fetchBySelect() {
  // 只为 state 绑定 typeOptions 的 value
  let state = selectedType.value
  if (state === '0') state = ''
  if (selectedAct.value === '0' && selectedAsset.value === '0') {
    recordDepositBank.run({ state } as any)
  } else if (selectedAct.value === '1' && selectedAsset.value === '0') {
    recordWithdrawBank.run({ state } as any)
  } else if (selectedAct.value === '0' && selectedAsset.value === 'crypto') {
    recordDepositCoin.run({ state } as any)
  } else if (selectedAct.value === '1' && selectedAsset.value === 'crypto') {
    recordWithdrawCoin.run({ state } as any)
  } else if (selectedAct.value === '2') {
    financeRecordOther.run()
  }
}

const currentList = computed(() => {
  let raw: any[] = []
  if (selectedAct.value === '0' && selectedAsset.value === '0') {
    raw = recordDepositBank.data.value?.d || []
  } else if (selectedAct.value === '1' && selectedAsset.value === '0') {
    raw = recordWithdrawBank.data.value?.d || []
  } else if (selectedAct.value === '0' && selectedAsset.value === 'crypto') {
    raw = recordDepositCoin.data.value?.d || []
  } else if (selectedAct.value === '1' && selectedAsset.value === 'crypto') {
    raw = recordWithdrawCoin.data.value?.d || []
  } else if (selectedAct.value === '2') {
    raw = financeRecordOther.data.value?.d || []
    // 根据选中的 tab 筛选数据
    if (activeTab.value > 0) { // 不是"全部"选项
      const selectedType = tabList.value[activeTab.value].label
      raw = raw.filter(item => item.cash_type_name === selectedType)
    }
  }
  return raw.map(item => {
    if (selectedAct.value === '2') {
      return {
        type: item.cash_type_name || '',
        time: formatTimestamp(item.created_at),
        amount: Number(item.amount),
        currency: item.currency_name,
        icon: item.currency_id
      }
    }
    return {
      type: item.pay_method_name || '',
      time: formatTimestamp(item.created_at), 
      amount: Number(item.pay_amount || item.finally_amount),
      currency: item.currency_name,
      icon: item.currency_id
    }
  })
})

onMounted(() => {
  fetchBySelect()
})

watch([selectedAct, selectedAsset, selectedType], fetchBySelect)
  
</script>
<template>
<div class="bg-[#23272b] min-h-screen text-white flex flex-col items-center py-4 px-4">
    <!-- 筛选区 -->
    <div class="w-full max-w-2xl grid grid-cols-2 gap-4 mb-4">
      <div class="flex flex-col gap-2">
        <AppSelectPick
          v-model="selectedAct"
          :options="otherOptions"
          :placeholder="t('select_act')"
        />
        <AppSelectPick
          v-model="selectedTime"
          :options="timeOptions"
          :dateRange="dateRange"
          @update:dateRange="dateRange = $event"
          :placeholder="t('select_time')"
        />
      </div>
      <div class="flex flex-col gap-2">
        <AppSelectPick
          v-model="selectedAsset"
          :options="dynamicAssetOptions"
          :placeholder="t('select_asset')"
        />
        <AppSelectPick
          v-model="selectedType"
          :options="typeOptions"
          :placeholder="t('select_type')"
        />
      </div>
    </div>
    <div class="w-full max-w-2xl text-xs text-[#b5b5b5] mb-2 flex items-center"
    @click="showQuestionModal = true">
      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
      {{ t('deposit_dispute_tip') }}
    </div>
    <!-- tab 切换 -->
    <div class="trade-tabs" v-if="selectedAct === '2'">
        <div
        v-for="(tab, idx) in tabList"
        :key="tab.label"
        class="tab"
        :class="{ active: activeTab === idx }"
        @click="setTab(idx)"
        >
        {{ tab.label }}
        </div>
    </div>
    <!-- 列表 -->
    <div class="w-full max-w-2xl">
      <TradeList :list="currentList" :selected-act="selectedAct" />
    </div>
    <questionModel v-model="showQuestionModal" />
</div>
  
</template>
<style scoped>
.trade-tabs {
    width: 100%;
  background: #292D2E;
  display: flex;
  gap: 8px;
  border-radius: 8px;
  margin-bottom: 16px;
}
.tab {
  flex: 1;
  border-radius: 4px;
  padding: 8px 0;
  text-align: center;
  color: #B3BEC1;
  cursor: pointer;
}
.tab.active {
  background: #3A4142;
  color: #fff;
  border-radius: 4px;
}
</style>


